import React, { Component } from 'react';
import {Button, Form, Input, Checkbox, Switch, Spin, Radio, Row, Col, Select} from 'antd'
import { messages } from "share/common";
const FormItem = Form.Item;
const Group = Checkbox.Group;
const { Option } = Select;
import 'styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss'
import NewConsumerServer from '../new-consumer-server'
class CtripEditFrame extends Component{

  constructor(props){
    super(props);
    this.state = {
      editData: {},
      loading: false,
      mode: 1,
      appKeyOptions: [],
      appSecurityOptions: []
    };
    this.options = [
      { label: messages('request.key325'/*机票*/), value: 'AIR' },
      { label: messages('request.key414'/*酒店*/), value: 'HOTEL' },
      { label: messages('supplier.key474')/*火车*/, value: 'TRAIN' },
      { label: messages('supplier.key475')/*用车*/, value: 'CAR' },
      { label: messages('supplier.key634')/*授权*/, value: 'ACCREDIT' },
    ];
  }

  componentWillMount() {
    NewConsumerServer(this).getCtripAPPKeyList().then(res => {
      let appKeyMap = new Map();
      if(res.data && res.data.body && res.data.body.length) {
        res.data.body.map(item => appKeyMap.set(item.appKey, item.appSecurity));
      }
      this.setState({ appKeyMap });
    });
  }

  componentWillReceiveProps(nextProps){
    const { params } = nextProps;
    const { data, index } = params;
    const { editData } = this.state;
    if(data && data.length && JSON.stringify(data[index]) !== JSON.stringify(editData)) {
      this.setState({
        editData: JSON.parse(JSON.stringify(data[index])),
        mode: data[index].isBigCus
      })
    }

  }

  onCancelEdit = () => {
    const { editData } = this.state;
    this.props.close();
    this.props.form.resetFields();
    this.setState({  mode: editData.isBigCus });
  };

  handleModeChange = e => {
    const mode = e.target.value;
    const { isBigCus, appKey, appSecurity, accountID, openType, isOpenApproval, isOpenPcSso,
      status } = this.state.editData;
    //切换相反tab的时候要清空带入值 账户类型可能为未配置但默认进入大客户  resetFields会重置为初始值非清空
    this.props.form.setFieldsValue((mode === isBigCus || (mode === 1 && isBigCus === 0)) ? {
      appKey,
      appSecurity,
      accountID,
      isOpenApproval,
      isOpenPcSso,
      'vendorTypes': openType && openType.split("|"),
      'isOpen': status === 1,
    } : {
      'appKey': null,
      'appSecurity': null,
      'accountID': null,
      'isOpenApproval': null,
      'isOpenPcSso': null,
      'vendorTypes': null,
      'isOpen': null,
    });
    this.setState({ mode });
  };

  onSubmitEdit = () => {
    const { mode } = this.state;
    if(!this.isLock){
      this.isLock = true;
    } else {
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        const upParams = Object.assign({},{
          isBigCus: !(mode === -1),
          companyList:[
            {
              companyOID: this.state.editData.companyOID,
              companyName: values.companyName,
            }
          ],
        }, values);
        delete upParams.companyOid;
        delete upParams.companyName;
        NewConsumerServer(this).submitCritpData(upParams).then(res => {
          this.isLock = false;
          this.props.close(true);
          this.props.form.resetFields();
        });
      } else {
        this.isLock = false;
      }
    })
  };

  onCreatAccount = () => {
    this.isLock = true;
    const { appKeyMap } = this.state;
    let values = this.props.form.getFieldsValue();
    const upParams = Object.assign({},{
      isBigCus: false,
      companyList:[
        {
          companyOID: this.state.editData.companyOID,
          companyName: values.companyName,
        }
      ],
    }, values);
    delete upParams.companyOid;
    delete upParams.companyName;
    delete upParams.appKey;
    delete upParams.appSecurity;
    NewConsumerServer(this).creatCritpAccount(upParams).then(res => {
      this.isLock = false;
      let data = res.data[0];
      this.setState({appKeyMap: appKeyMap.set(data.appKey, data.appSecurity)});
      this.props.form.setFieldsValue(Object.assign(data, {
        'appKey': data.appKey,
        'appSecurity': data.appSecurity,
        'vendorTypes': data.openType && data.openType.split("|"),
        'isOpen': data.status === 1,
        'isOpenApproval': data.openApproval,
        'isOpenPcSso': data.openPcSso
      }));
    });
  };

  onChangeAppKey = value => {
    const { appKeyMap } = this.state;
    this.props.form.setFieldsValue({ 'appSecurity': appKeyMap.get(value) });
  };

  isOpenServer = (value) => {
    if(!value){
      this.props.form.setFieldsValue({isOpenPcSso: false});
      this.props.form.setFieldsValue({isOpenApproval: false});
      this.props.form.setFieldsValue({vendorTypes: []});
    }
  }

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { editData, loading, mode, appKeyMap } = this.state;
    const { companyCode, isBigCus, companyName, appKey, appSecurity, accountID, openType, isOpenApproval, isOpenPcSso, status } = editData;

    const formLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    return (
      <div className='edit-frame'>
        <Spin spinning={loading}>
          <Form>
            <Row>
              <Col offset={6} span={16} >
                <Radio.Group onChange={this.handleModeChange} value={mode === -1 ? -1 : 1} style={{ marginBottom: 32 }}>
                  <Radio.Button value={1}>{messages('supplier.key485')/*携程大客户*/}</Radio.Button>
                  <Radio.Button value={-1}>{messages('supplier.key486')/*携程小客户*/}</Radio.Button>
                </Radio.Group>
              </Col>
            </Row>
            <FormItem label={messages('components.key17'/*公司代码*/)} {...formLayout}>
              {
                getFieldDecorator('companyCode',{
                  initialValue: companyCode || '',
                })(
                  <Input disabled />
                )
              }
            </FormItem>
            <FormItem label={messages('components.key18'/*公司名称*/)} {...formLayout}>
              {
                getFieldDecorator('companyName',{
                  initialValue: companyName || '',
                })(
                  <Input disabled />
                )
              }
            </FormItem>
            {/*需求变更：如果公司已经是小客户则不许新建小客户账号 留了个口子如果是小客户并且还没拿到appKey可以新建，正常应该不会出现*/}
            {mode === -1 && (isBigCus !== -1 || !appKey) && (
              <Row>
                <Col offset={6} span={16} >
                  <Button type="link" icon="plus" style={{ marginLeft: -15 }} onClick={this.onCreatAccount}>
                    {messages('supplier.key476')/*新建携程账户*/}
                  </Button>
                  <p style={{ marginBottom: 32, fontSize: 12 }} className='font-subtitle'>{messages('supplier.key487')/*首个携程小客户权限需要在线新建，成功后会回写App Key, App Secret*/}</p>
                </Col>
              </Row>
            )}
            <FormItem label={'App Key'} {...formLayout}>
              {
                getFieldDecorator('appKey',{
                  initialValue: mode === -1 ? [...appKeyMap.keys()][0] : (appKey || ''),
                  rules:[
                    { required:true, message:messages('components.key506'/*必填*/) }
                  ]
                })(
                  mode === -1 ? (
                    <Select onChange={this.onChangeAppKey}>
                      {[...appKeyMap.keys()].map(option => <Option value={option}>{option}</Option>)}
                    </Select>
                  ) :
                    <Input />
                )
              }
            </FormItem>
            <FormItem label={'App Secret'} {...formLayout}>
              {
                getFieldDecorator('appSecurity',{
                  initialValue: mode === -1 ? [...appKeyMap.values()][0] : (appSecurity || ''),
                  rules:[
                    { required:true, message:messages('components.key506'/*必填*/) }
                  ]
                })(
                  mode === -1 ? <Select disabled/> : <Input />
                )
              }
            </FormItem>
            <FormItem label={'Account ID'} {...formLayout} style={mode === -1 ? {display: 'none'}: {}}>
              {
                getFieldDecorator('accountID',{
                  initialValue: accountID || '',
                })(
                   <Input />
                )
              }
            </FormItem>
            <FormItem style={{display:"flex",alignItems:'center'}} label={messages('setting.key1738'/*开通服务*/)} {...formLayout}>
              {
                getFieldDecorator('vendorTypes',{
                  initialValue: openType ? openType.split("|") : [],
                  rules:[
                    {required: getFieldValue('isOpen'), message: messages('components.key506'/*必填*/)}
                  ]
                })(<Group options={this.options}/>)
              }
            </FormItem>
            <FormItem label={messages('loan-billing.key71')/*关联申请单*/} {...formLayout}>
              {
                getFieldDecorator('isOpenApproval',{
                  initialValue: !!isOpenApproval || false,
                  valuePropName: 'checked',
                })(
                  <Switch />
                )
              }
            </FormItem>
            <FormItem label={messages('supplier.key292')/*PC端入口*/} {...formLayout}>
              {
                getFieldDecorator('isOpenPcSso',{
                  initialValue: !!isOpenPcSso || false,
                  valuePropName:'checked',
                })(
                  <Switch />
                )
              }
            </FormItem>
            <FormItem style={{ marginBottom: window.ISIE9 ? 80 : 0 }} label={messages('setting.key289'/*状态*/)} {...formLayout}>
              {
                getFieldDecorator('isOpen',{
                  initialValue: status === 1 || false,
                  valuePropName:'checked',
                })(
                  <Switch onChange={this.isOpenServer}/>
                )
              }
            </FormItem>
          </Form>
        </Spin>
        <div className='affix-bottom'>
          <Button onClick={this.onCancelEdit}>
            {messages('common.cancel')/*取消*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button type="primary"  onClick={this.onSubmitEdit} loading={this.isLock}>
            {messages('common.ok')/*确定*/}
          </Button>
        </div>
      </div>
    )
  }
}

const wrapperCtripEditFrame = Form.create()(CtripEditFrame);

wrapperCtripEditFrame.getEditData = (record, data, index) => {
  return {data, index};
};

export default wrapperCtripEditFrame;


